var express = require('express');
var path = require('path');
var fs = require('fs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const multer = require('multer');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
const dir = path.resolve(__dirname, 'public/images');
const SIZELIMIT = 500000;

//跨域
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {

        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});

app.use('/', indexRouter);
app.use('/users', usersRouter);

const storage = multer.diskStorage({
    // 指定文件路径
    destination: function(req, file, cb) {
        cb(null, dir);
    },
    // 指定文件名
    filename: function(req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
});

const upload = multer({
    storage: storage
});

app.post('/upload', upload.single('image'), (req, res) => {
    // 即将上传图片的key值 form-data对象{key: value}
    // 检查是否有文件待上传
    if (req.file === undefined) {
        return res.send({
            errno: -1,
            msg: 'no file'
        });
    }
    const {size, mimetype, filename} = req.file;
    const types = ['jpg', 'jpeg', 'png', 'gif'];
    const tmpTypes = mimetype.split('/')[1];
    // 检查文件大小
    if (size >= SIZELIMIT) {
        return res.send({
            success: 0,
            msg: 'file is too large'
        });
    }
    // 检查文件类型
    else if (types.indexOf(tmpTypes) < 0) {
        return res.send({
            success: 0,
            msg: 'not accepted filetype'
        });
    }
    // 路径可根据设置的静态目录指定
    const url = 'http://39.108.95.115:8083/images/' + filename;
    res.json({
        success: 1,
        msg: 'upload success',
        file: {
            url :  url
            // ... and any additional fields you want to store, such as width, height, color, extension, etc
        }
    });
});


app.post("/save",function (req,res) {

    console.log(req.body.content);
    fs.writeFile('./public/articles/article.txt', req.body.content, function(err) {
        if (!err) {
            return res.json({status:1});
        }
    });
})

app.post("/article",function (req,res) {
    fs.readFile("./public/articles/article.txt",function (err,doc) {
        if(!err){
            res.json({status: 1,content:doc.toString()})
        }
    });
})
app.listen(8089, () => {
    console.log('service start');

});


module.exports = app;
